import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/13 13:22
 * @description 滑动窗口
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.longestSubstring("ababbc", 2);
    }
    public int longestSubstring(String s, int k) {
        int ret = 0, n = s.length();
        // 对子串出现的字符种类数目进行枚举
        for (int t = 1; t<=26; t++) {
            int left = 0, right = 0;
            // 单个字符出现的次数计数
            int[] cnt = new int[26];
            // tol代表滑动窗口内的字符种类数目，less代表当前出现次数小于k的字符数量
            int tol = 0, less = 0;
            while (right < n) {
                int index = s.charAt(right) - 'a';
                cnt[index]++;
                if (cnt[index] == 1) {
                    // 出现字符种类加1
                    tol++;
                    // 出现次数小于k的字符加1
                    less++;
                }
                if (cnt[index] == k) {
                    less--;
                }
                while (tol > t) {
                    // 当出现字符种类大于枚举种类
                    int index2 = s.charAt(left) - 'a';
                    cnt[index2]--;
                    if (cnt[index2] == k-1) {
                        less++;
                    }
                    if (cnt[index2] == 0) {
                        tol--;
                        less--;
                    }
                    left++;
                }

                if (less == 0) {
                    ret = Math.max(ret, right - left + 1);
                }
                right++;
            }
        }
        return ret;
    }
}
